package com.xq.shop.controller.admin;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.xq.shop.po.Product;
import com.xq.shop.po.ProductImage;
import com.xq.shop.service.admin.IBaseService;
import com.xq.shop.service.admin.IProductService;
import com.xq.shop.util.AdminServiceFactory;
import com.xq.shop.util.GsonUtil;
import com.xq.shop.util.NameComparator;
import com.xq.shop.util.RespUtil;
import com.xq.shop.util.SizeComparator;
import com.xq.shop.util.TypeComparator;
import com.xq.shop.vo.BrowserResult;
import com.xq.shop.vo.RespMsg;
import com.xq.shop.vo.SearchObject;
import com.xq.shop.vo.UploadResult;
import com.xq.shop.vo.RespMsg.Result;

@Controller
@RequestMapping("admin/")
public class ProductController extends BaseController<Product> {

	IProductService productService = AdminServiceFactory.getProductService();

	@SuppressWarnings("unchecked")
	@RequestMapping("product_iamge_borwser.do")
	@ResponseBody
	public String browser(HttpServletRequest request,HttpServletResponse response) {


		//根目录路径，可以指定绝对路径，比如 /var/www/upload/
		String rootPath = request.getSession().getServletContext().getRealPath("/") + "\\upload\\";
		
		//根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/upload/
		String rootUrl  = getUploadURL(request) + "/upload/";
		
		//图片扩展名
		String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};

//		String dirName = request.getParameter("dir");
//		if (dirName != null) {
//			if(!Arrays.<String>asList(new String[]{"image", "flash", "media", "file"}).contains(dirName)){
//				System.out.println("Invalid Directory name.");
//				//return "";
//			}
//			
//			rootPath += dirName + "/";
//			rootUrl += dirName + "/";
//			File saveDirFile = new File(rootPath);
//			if (!saveDirFile.exists()) {
//				saveDirFile.mkdirs();
//			}
//		}
		
		//根据path参数，设置各路径和URL
		String path = request.getParameter("path") != null ? request.getParameter("path") : "";
		String currentPath = rootPath + path;
		String currentUrl = rootUrl + path;
		String currentDirPath = path;
		String moveupDirPath = "";
		if (!"".equals(path)) {
			String str = currentDirPath.substring(0, currentDirPath.length() - 1);
			moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
		}

		//排序形式，name or size or type
		String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";

		//不允许使用..移动到上一级目录
		if (path.indexOf("..") >= 0) {
			System.out.println("Access is not allowed.");
			return "";
		}
		//最后一个字符不是/
		if (!"".equals(path) && !path.endsWith("/")) {
			System.out.println("Parameter is not valid.");
			return "";
		}
		//目录不存在或不是目录
		File currentPathFile = new File(currentPath);
		if(!currentPathFile.isDirectory()){
			System.out.println("Directory does not exist.");
			return "";
		}

		//遍历目录取的文件信息
		List<Hashtable> fileList = new ArrayList<Hashtable>();
		if(currentPathFile.listFiles() != null) {
			
			for (File file : currentPathFile.listFiles()) {
				Hashtable<String, Object> hash = new Hashtable<String, Object>();
				String fileName = file.getName();
				if(file.isDirectory()) {
					hash.put("is_dir", true);
					hash.put("has_file", (file.listFiles() != null));
					hash.put("filesize", 0L);
					hash.put("is_photo", false);
					hash.put("filetype", "");
				} else if(file.isFile()){
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					hash.put("is_dir", false);
					hash.put("has_file", false);
					hash.put("filesize", file.length());
					hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
					hash.put("filetype", fileExt);
				}
				hash.put("filename", fileName);
				hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
				fileList.add(hash);
			}
		}

		if ("size".equals(order)) {
			Collections.sort(fileList, new SizeComparator());
		} else if ("type".equals(order)) {
			Collections.sort(fileList, new TypeComparator());
		} else {
			Collections.sort(fileList, new NameComparator());
		}
		
		BrowserResult result = new BrowserResult();
		result.setMoveup_dir_path(moveupDirPath);
		result.setCurrent_dir_path(currentDirPath);
		result.setCurrent_url(currentUrl);
		result.setTotal_count(fileList.size());
		result.setFile_list(fileList);

		return GsonUtil.toJson(result);
	}

	@RequestMapping("product_delete.do")
	public void delete(String id, HttpServletResponse response){
		
		super.delete(id, response);
	}

	@RequestMapping("product_edit.do")
	public ModelAndView edit(String id) {

		ModelAndView modelAndView = new ModelAndView(
				"admin/product/product_edit");
		Product product;
		if (id != null) {
			product = productService.get(Long.parseLong(id));
		} else {
			product = new Product();
		}

		if (product == null) {
			// TODO goto 404
			return modelAndView;
		} else {
			
			if(StringUtils.isNotBlank(product.getContent())){
				String content = product.getContent().replace("\r\n\t", "").replace("\r\n", "");	//处理textarea内容换行问题
				product.setContent(content);
			}
			modelAndView.addObject("entity", product);
			return modelAndView;
		}
	}

	@Override
	public IBaseService<Product> getService() {
		return productService;
	}

	/**
	 * 服务器提供服务的地址
	 * @param request
	 * @return
	 */
	private String getUploadURL(HttpServletRequest request) {
		return request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + request.getContextPath();
	}

	@RequestMapping("product_list.do")
	@ResponseBody
	public String list(SearchObject search){
		return GsonUtil.toJson(productService.get(search));
	}

	@RequestMapping("product_save.do")
	public ModelAndView save(Product product, HttpServletRequest request,
			HttpServletResponse response) {

		/*
		 * 处理商品图片
		 */
		CommonsMultipartResolver cmr = new CommonsMultipartResolver(request
				.getSession().getServletContext());
		List<ProductImage> productImageList = product.getImages();

		if (cmr.isMultipart(request)) { // 判断是否上传图片

			MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);
			Iterator<String> files = mRequest.getFileNames();

			while (files.hasNext()) {

				String paramName = files.next(); // 参数name值
				MultipartFile mFile = mRequest.getFile(paramName); // 获取文件
				if (mFile != null && !mFile.isEmpty()) { // 判断文件不为空

					try {

						//文件上传目录已日期来划分
						String fileName = UUID.randomUUID() + mFile.getOriginalFilename(), 
								path = request.getSession().getServletContext().getRealPath("/"),
								dir = "/upload/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/";

						if (!new File(path + dir).exists()){
							
							File directory = new File(path + dir);	
							//创建目录
							directory.mkdirs();
						}  
						
						File localFile = new File(path + dir + fileName);
						mFile.transferTo(localFile);
						
						String fileIndex = paramName.split("_")[1],
								fileTitle = request.getParameter("fileTitle_" + fileIndex),
								fileSeq = request.getParameter("fileSeq_" + fileIndex);

						ProductImage image = new ProductImage();
						image.setUrl(getUploadURL(request) + dir + fileName);
						image.setSeq(StringUtils.isBlank(fileSeq) ? 0 : Integer.parseInt(fileSeq));
						image.setTitle(fileTitle);
						productImageList.add(image);
					} catch (Exception e) {
						System.out.println("图片上传失败："
								+ mFile.getOriginalFilename());
						e.printStackTrace();
					}
				}
			}
		}
		productService.saveOrUpdate(product);
		ModelAndView modelAndView = new ModelAndView(
				"admin/product/product_list");
		modelAndView.addObject(new RespMsg(Result.success, "保存成功"));
		return modelAndView;
	}
	
	@RequestMapping("product_iamge_upload.do")
	public void uploadImage(HttpServletRequest request,
			HttpServletResponse response) {

		CommonsMultipartResolver cmr = new CommonsMultipartResolver(request
				.getSession().getServletContext());

		if (cmr.isMultipart(request)) { // 判断是否上传图片

			MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);
			Iterator<String> files = mRequest.getFileNames();

			while (files.hasNext()) {

				String paramName = files.next(); // 参数name值
				MultipartFile mFile = mRequest.getFile(paramName); // 获取文件
				UploadResult result = new UploadResult();
				if (mFile != null && !mFile.isEmpty()) { // 判断文件不为空

					try {

						String fileName = UUID.randomUUID() + mFile.getOriginalFilename(), 
								path = request.getSession().getServletContext().getRealPath("/"),
								dir = "/upload/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/";

						if (!new File(path + dir).exists()){
							File directory = new File(path + dir);	
							directory.mkdirs(); 
						}  
						
						File localFile = new File(path + dir + fileName);
						mFile.transferTo(localFile);

						String url = getUploadURL(request) + dir + fileName;
						result = new UploadResult(url, "上传成功");
					} catch (Exception e) {
						System.out.println("图片上传失败："
								+ mFile.getOriginalFilename());
						e.printStackTrace();
						result = new UploadResult(UploadResult.FAIL, "", e.getMessage());
					} finally {
						RespUtil.renderJson(GsonUtil.toJson(result), response);
					}
				}
			}
		}
	}
}
